package com.wh.msg.entity;

import com.google.gson.Gson;
import com.wh.msg.entity.base64.Base64CoderCC;
import com.wh.msg.entity.payload.SignUpBody;
import com.wh.msg.entity.header.Header;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * JWT工具类
 * @author 谢泽鹏
 * @version V1.0
 * @Package com.wh.msg.entity
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
public class JwtUtil {

    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    /**
     * 错误消息
     */
    private static String errorMsg = "";


    /**
     * 返回转换出对象
     * @param jwtString  转换字符
     * @param jwtSignUp  转换返回对象
     * @return
     */
    public static Object jwtSignUp(String jwtString, JwtSignUp jwtSignUp){
        try{
            logger.info("jwtSignUp->>JWT解析字符串 jwtString: " + jwtString);
            logger.info("jwtSignUp->>JWT解析返回对象 jwtSignUp: " + jwtSignUp);
            //1. 分隔成数组
            String[] parent = jwtString.split(" ");
            //2. 分隔成body
            String[] result =  parent[1].toString().split("\\.");
            logger.info("jwtSignUp->>JWT解析字符串 header: " + result[0].toString());
            logger.info("jwtSignUp->>JWT解析字符串 playload: " + result[1].toString());

            Header header = (Header) jwtFormatHader(result[0].toString(), jwtSignUp.getHeader().getClass());
            SignUpBody bodySignUp = (SignUpBody) jwtFormatBody(result[1].toString(), jwtSignUp.getBodySignUp().getClass());
            String secret = jwtFormatSecret(result[2].toString());
            jwtSignUp.setHeader(header);
            jwtSignUp.setBodySignUp(bodySignUp);
            jwtSignUp.setSecret(secret);
        } catch (Exception e){
            e.printStackTrace();
            errorMsg = "jwtSignUp->>JWT解析字符串jwtAllSiginUp Exception : " + e.getMessage();
            logger.error(errorMsg);
            return new JwtSignUp();
        }
           return jwtSignUp;
    }


    /**
     * jwt的header处理
     * @param jwtHeader header字符串
     * @param <T>cls    header对象转换
     * @throws Exception
     */
    public static <T> Object jwtFormatHader(String jwtHeader, Class<T> cls) throws Exception {
        Object object = null;
        try{
            logger.info("jwtFormatHader->>JWT解析 jwtHeader: " + jwtHeader);
            jwtHeader = replace(jwtHeader);
            jwtHeader = Base64CoderCC.decode(jwtHeader);
            object = new Gson().fromJson(jwtHeader, cls);
        } catch (Exception e){
            e.printStackTrace();
            errorMsg = "jwtFormatHader->>JJWT解析字符串jwtFormatHader Exception : " + e.getMessage();
            throw new RuntimeException(errorMsg);
        }
            return (T) object;
    }


    /**
     * jwt的playload处理
     * @param jwtBody  jwtBody字符串
     * @param <T>cls   jwtBody对象转换
     * @throws Exception
     */
    public static <T> Object jwtFormatBody(String jwtBody, Class<T> cls) throws Exception{
        Object object = null;
        try{
            logger.info("jwtFormatPlayload->>JWT解析 jwtBody: " + jwtBody);
            jwtBody = replace(jwtBody);
            jwtBody = Base64CoderCC.decode(jwtBody);
            object = new Gson().fromJson(jwtBody, cls);
        } catch (Exception e){
            e.printStackTrace();
            errorMsg = "jwtFormatPlayload->>JWT解析字符串jwtFormatPlayload Exception : " + e.getMessage();
            throw new RuntimeException(errorMsg);
        }
            return object;
    }


    /**
     * jwt的Secret处理
     * @param jwtSecret jwtSecret字符串
     * @return
     * @throws Exception
     */
    public static String jwtFormatSecret(String jwtSecret) throws Exception{
        try{
            logger.info("jwtFormatSecret->>JWT解析 jwtSecret: " + jwtSecret);
            jwtSecret = replace(jwtSecret);
            //jwtSecret = Base64CoderCC.decode(jwtSecret);
        } catch (Exception e){
            e.printStackTrace();
            errorMsg = "jwtFormatSecret->>JWT解析字符串jwtFormatSecret Exception : " + e.getMessage();
            throw new RuntimeException(errorMsg);
        }
            return jwtSecret;
    }


    /**
     * 全局替换处理
     * @param thisStr 当前字符
     * @return
     */
    public static String replace(String thisStr){
        //1. 全局替换
        thisStr = thisStr.replaceAll("\\-", "+").replaceAll("\\_", "/");
        //2. 补全
        if (thisStr.length() % 4 != 0) {
            for (int i = 4 - thisStr.length() % 4; i > 0; i--) {
                thisStr += "=";
            }
        }
        return thisStr;
    }


    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        //可以正常使用
        //亲自测试☎☏✄☪☣☢☠♨« »큐〓㊚㊛囍㊒㊖☑✔☐☒✘㍿☯☰☷♥♠♤❤♂♀★☆☯✡※卍卐■找一个好姑娘@%#$^&*1234567890~`!?;:',.=+-/r/n做老婆是我的梦 想！
        //String jwtString = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.4piO4piP4pyE4piq4pij4pii4pig4pmowqsgwrvtgZDjgJPjiprjipvlm43jipLjipbimJHinJTimJDimJLinJjjjb-imK-imLDimLfimaXimaDimaTinaTimYLimYDimIXimIbimK-inKHigLvljY3ljZDilqDmib7kuIDkuKrlpb3lp5HlqJhAJSMkXiYqMTIzNDU2Nzg5MH5gIT87OicsLj0rLQoN5YGa6ICB5amG5piv5oiR55qE5qKmIOaDs--8gQ.OyqdadieZ3fvDq1miHKPS2cFN1KK4-jC5DqDY9JFvfY";

        String jwtString = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJRVk9jUEZUT2dScjFVSmNvTldtVWRlTmJuUFlCOWtIMSIsIm9wZW5faWQiOiJSRWdFZTYyZHF5QklXSXVBWDBYSG9vRXFWaXpMeUdmNUlfcThybGZMX3ZNIn0.49UF72vSkj-sA4aHHiYN5eoZ9Nb4w5Vb45PsLF7x_NY";
        JwtSignUp jwtSignUp = new JwtSignUp();
        jwtSignUp = (JwtSignUp) jwtSignUp(jwtString, jwtSignUp);
        System.out.println();
        System.out.println("jwtSignUp.getHeader().getAlg()： "  + jwtSignUp.getHeader().getAlg());
        System.out.println("jwtSignUp.getHeader().getTyp()： "  + jwtSignUp.getHeader().getTyp());
        System.out.println("jwtSignUp.getBodySignUp().getIss()： "  + jwtSignUp.getBodySignUp().getIss());
        System.out.println("jwtSignUp.getBodySignUp().getOpen_id()： "  + jwtSignUp.getBodySignUp().getOpen_id());
        System.out.println("jwtSignUp.getSecret()： "  + jwtSignUp.getSecret());


        String jwtBodyString = "eyJpc3MiOiJRVk9jUEZUT2dScjFVSmNvTldtVWRlTmJuUFlCOWtIMSIsIm9wZW5faWQiOiJSRWdFZTYyZHF5QklXSXVBWDBYSG9vRXFWaXpMeUdmNUlfcThybGZMX3ZNIn0";
        SignUpBody signUpBody  = (SignUpBody) jwtFormatBody(jwtBodyString, SignUpBody.class);
        System.out.println("signUpBody.getIss()： "  + signUpBody.getIss());
        System.out.println("signUpBody.getOpen_id()： "  + signUpBody.getOpen_id());


    }


}
